#!/usr/bin/perl

use warnings;
use strict;
use FindBin;
use lib "$FindBin::Bin/../lib";
use ReefStats::Schema::ReefStatsDB;
use Data::Dumper;

my $schema = ReefStats::Schema::ReefStatsDB->connect_via_config();

{
    my $ml = $schema->resultset('ActionsDomain');
    my $d  = $schema->resultset('Domains');

    my $rs =
      $ml->search( undef,
        { select => [ { distinct => [qw(domain)] } ], as => [qw(domain)] } );

    while ( my $row = $rs->next ) {
        print $row->get_column('domain'), "\n";
        $d->find_or_create( domain => $row->get_column('domain') );

    }
}

{
    my $ml = $schema->resultset('ActionsUser');
    my $u  = $schema->resultset('Users');
    my $d  = $schema->resultset('Domains');
    my $standard_user_role =
      $schema->resultset('Roles')
      ->find_or_create( { role => 'standard_user', } );

    my $rs =
      $ml->search( undef,
        { select => [ { distinct => [qw(user)] } ], as => [qw(user)] } );

    while ( my $row = $rs->next ) {
        print $row->get_column('user'), "\n";
        my $user =
          $u->find_or_create( email_address => $row->get_column('user') );
        $user->add_to_roles($standard_user_role)
          if ( !$user->roles->search( { role => $standard_user_role } ) );
        my $domain = $user->email_address();
        $domain =~ s/^.*\@//;
        $domain = $d->search( { domain => $domain } );
        if ($domain) {
            $user->domain( $domain->first );
        }
        $user->update();
        print $user->email_address(), "\n";
    }
}

1;
